import 'package:flutter/material.dart';
import 'package:get_it/get_it.dart';
import '../common/button_color.dart';
import '../common/tag.dart';
import '../common/custom_bottom_sheet.dart';
import '../common/memo_category.dart';
import 'memo.dart';

class MemoEditScreen extends StatefulWidget {
  final Memo memo;
  const MemoEditScreen({Key? key, required this.memo}) : super(key: key);

  @override
  MemoEditScreenState createState() => MemoEditScreenState();
}

class MemoEditScreenState extends State<MemoEditScreen> {
  final _formKey = GlobalKey<FormState>();
  final TextEditingController _tagController = TextEditingController();
  late TextEditingController _categoryController;
  late String _title, _content, _category;

  @override
  void initState() {
    super.initState();
    _categoryController = TextEditingController(text: widget.memo.category);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('编辑备忘录'),
      ),
      body: Builder(builder: (BuildContext context) {
        return SingleChildScrollView(
          child: Padding(
            padding: const EdgeInsets.all(16),
            child: Form(
              key: _formKey,
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.stretch,
                children: [
                  TextFormField(
                    decoration: const InputDecoration(labelText: '标题'),
                    initialValue: widget.memo.title,
                    validator: (value) {
                      if (value == null || value.isEmpty) {
                        return '请输入标题';
                      }
                      return null;
                    },
                    onSaved: (value) {
                      _title = value!;
                    },
                  ),
                  const SizedBox(height: 16),
                  TextFormField(
                    decoration: const InputDecoration(labelText: '内容'),
                    initialValue: widget.memo.content,
                    minLines: 10,
                    maxLines: null,
                    validator: (value) {
                      if (value == null || value.isEmpty) {
                        return '请输入内容';
                      }
                      return null;
                    },
                    onSaved: (value) {
                      _content = value!;
                    },
                  ),
                  const SizedBox(height: 16),
                  TextFormField(
                    decoration: const InputDecoration(
                      labelText: '所属分类',
                      suffixIcon: Icon(Icons.arrow_drop_down),
                    ),
                    controller: _categoryController,
                    maxLines: 1,
                    validator: (value) {
                      if (value == null || value.isEmpty) {
                        return '请选择分类';
                      }
                      return null;
                    },
                    onTap: () async {
                      int? selectedIndex =
                          await CustomBottomSheet.showCustomModalBottomSheet(
                              context, '选择分类', MemoCategory.categoryList);
                      if (selectedIndex != null) {
                        _category = MemoCategory.categoryList[selectedIndex];
                        setState(() {
                          _categoryController.text = _category;
                        });
                      }
                    },
                  ),
                  const SizedBox(
                    height: 16,
                  ),
                  Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Wrap(
                        alignment: WrapAlignment.start,
                        spacing: 4.0,
                        runSpacing: 4.0,
                        children: [
                          for (final tag in widget.memo.tags)
                            Tag(
                              text: tag,
                              onDeleted: () => _removeTag(tag),
                            )
                        ],
                      ),
                      TextField(
                        controller: _tagController,
                        decoration: InputDecoration(
                          labelText: '添加标签',
                          suffixIcon: IconButton(
                            icon: const Icon(Icons.add),
                            onPressed: _addTag,
                          ),
                        ),
                        onSubmitted: (_) => _addTag(),
                      ),
                    ],
                  ),
                  const SizedBox(height: 16),
                  ElevatedButton(
                    style: ButtonStyle(
                      backgroundColor: PrimaryButtonColor(
                        context: context,
                      ),
                    ),
                    onPressed: () async {
                      if (_formKey.currentState!.validate()) {
                        _formKey.currentState!.save();
                        await _saveMemo(context);
                        _showSnackBar(context, '备忘录已保存');
                        Navigator.of(context).pop(1);
                      }
                    },
                    child: const Text(
                      '保 存',
                      style: TextStyle(color: Colors.black, fontSize: 16.0),
                    ),
                  ),
                ],
              ),
            ),
          ),
        );
      }),
    );
  }

  Future<void> _saveMemo(BuildContext context) async {
    widget.memo.title = _title;
    widget.memo.content = _content;
    widget.memo.category = _category;
    widget.memo.modifiedTime = DateTime.now();
    // 保存备忘录
    await GetIt.I<MemoDao>().updateMemo(widget.memo);
  }

  void _showSnackBar(BuildContext context, String message) async {
    ScaffoldMessenger.of(context)
        .showSnackBar(SnackBar(content: Text(message)));
  }

  void _addTag() {
    final newTag = _tagController.text.trim();
    if (newTag.isNotEmpty && !widget.memo.tags.contains(newTag)) {
      setState(() {
        widget.memo.tags.add(newTag);
        _tagController.clear();
      });
    }
  }

  void _removeTag(String tag) {
    setState(() {
      widget.memo.tags.remove(tag);
    });
  }
}
